<template>
    <div class="iframe-full">
        <div class="iframe-preview">
            <div class="head">
                <div class="top">
                    <span class="time">10:00</span>
                    <div class="icons">
                        <img src="@/assets/mall/micon.png" class="micon" /><img
                            src="@/assets/mall/dicon.png"
                            class="dicon" /><img src="@/assets/mall/picon.png" class="picon" />
                    </div>
                </div>
                <div class="bottom" @click="changeTOhead">
                    <div class="shopname elispse">
                        <span v-if="isHomePage == 1">{{ shopName }} </span>
                    </div>
                    <div class="name elispse">{{ templateDesc }}</div>
                    <div class="bicon"><img src="@/assets/mall/bicon.png" class="sicon" /></div>
                </div>
            </div>
            <div v-if="isHomePage == 3" class="out">
                <img :src="payresultImg" onerror="@/assets/mall/bicon.png" class="payImg" />
            </div>
            <div
                v-for="(element, index) in components"
                :key="element"
                class="component-body"
                @click="
                    passValueToParent(index, {
                        id: element.id,
                        name: element.component.name
                    })
                ">
                <div class="component-center">
                    <component
                        class="component-item"
                        :tabindex="index"
                        :is="element.component"
                        :options="element.options"
                        :id="`com${element.id}`">
                    </component>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, nextTick, onMounted, getCurrentInstance } from 'vue';
import { getComponentByName } from '@/components';
import { getUrlParam, floatDivide, isNotEmpty } from '@/commons/utils';
import IframeMessage from '@/commons/iframeMessage';

import request from '@/request';
import { useRouter } from 'vue-router';
const router = useRouter();
let shopName = ref();
let isHomePage = ref();
let templateDesc = ref();
let payresultImg = ref();
let components = ref([]);
const instance = getCurrentInstance();
const iframeMessage = new IframeMessage(window.parent, `${import.meta.env.VITE_SHOP_CLOUD_HOST}`);
/**
 * 改变iframe高度
 */
const changeIframeHeight = () => {
    nextTick(() => {
        let heightArr = [];
        components.value.forEach((res, i) => {
            uni.createSelectorQuery()
                .in(instance)
                .select('#com' + res.id)
                .boundingClientRect(data => {
                    heightArr.push(data.height);
                })
                .exec();
        });
        iframeMessage.emit('changeMaskHeight', heightArr);
        uni.createSelectorQuery()
            .in(instance)
            .select('.iframe-full')
            .boundingClientRect(data => {
                iframeMessage.emit('changeIframeHeight', data.height);
            })
            .exec();
    });
};
// 转换优惠券内容
const couponContent = obj => {
    const { couponPrerequisites, couponMatch, couponPrerequisitesAdditional, couponDiscountContent } = obj;
    const pre = [
        '无门槛，',
        `满${floatDivide(couponPrerequisitesAdditional, 100)}元，`,
        `满${couponPrerequisitesAdditional}件，`
    ];
    const num = [`全部商品`, `部分商品`, '部分商品'];
    return (pre[couponPrerequisites - 1] || '') + (num[couponMatch - 1] || '');
};
onMounted(async () => {
    const createTime = getUrlParam('createTime');
    const pageId = getUrlParam('pageId');
    shopName.value = getUrlParam('shopName');
    const nowTime = Date.now();
    //毫秒转化为分
    const time = (nowTime - createTime) / (60 * 1000);
    if (time > 1) {
        router.push({
            path: '../../pages/warn/index'
        });
    } else {
        // 编辑
        request('decorateServ', { id: pageId, isPreview: 1 }).then(async res => {
            let data = [];
            let productIds = [];
            let seckillIds = [];
            let groupbuyIds = [];
            let couponIds = [];
            isHomePage.value = res?.data?.isHomePage;
            templateDesc.value = res?.data?.templateDesc;
            // 获取支付结果默认图片
            if (isHomePage.value == 3) {
                const data = await request('payresultImg');
                payresultImg.value = data.data.paymentImg;
            }
            const param = JSON.parse(res.data.components);
            param.forEach(async (item, index) => {
                if (item.component.name == 'PlaceHolderView') {
                    param.splice(index, 1);
                    return;
                }
                delete item.component;
                item = { ...item, component: getComponentByName(item.options.name).component };
                if (item.component.name == 'product') {
                    productIds = [...productIds, ...item.options.imgList];
                } else if (item.component.name == 'seckill') {
                    seckillIds = [...seckillIds, ...item.options.imgList];
                } else if (item.component.name == 'groupbuy') {
                    if (item.options.addType == 1) {
                        groupbuyIds = [...groupbuyIds, ...item.options.imgList];
                    }
                } else if (item.component.name == 'coupon') {
                    couponIds = [...couponIds, ...item.options.imgList];
                }
                data.push(item);
            });
            let productData = [];
            let seckillData = [];
            let groupData = [];
            let couponData = [];
            if (couponIds.length) {
                couponData = await request('couponList', { couponIds: couponIds });
            }
            if (productIds.length) {
                productData = await request('goodsList', { goodsId: productIds });
            }
            if (seckillIds.length) {
                seckillData = await request('seckillList', { activityId: seckillIds });
            }
            if (groupbuyIds.length) {
                groupData = await request('seckillListManual', { activityId: groupbuyIds });
            }
            let getData = await Promise.all(
                data.map(async item => {
                    const name = item.component.name;
                    const imgLists = {
                        product: isNotEmpty(productData?.data) ? productData?.data : [],
                        seckill: isNotEmpty(seckillData?.data) ? seckillData?.data : [],
                        groupbuy: isNotEmpty(groupData?.data) ? groupData?.data : [],
                        coupon: isNotEmpty(couponData?.data) ? couponData?.data : []
                    };
                    if (name == 'product' || name == 'seckill') {
                        item.options.imgList.forEach((id, indexs) => {
                            let proItem = imgLists[name].filter(val => val.id == id);
                            if (proItem.length) {
                                item.options.imgList[indexs] = proItem[0];
                            } else {
                                item.options.imgList[indexs] = null;
                            }
                        });
                    }
                    if (name == 'coupon') {
                        item.options.imgList.forEach((id, indexs) => {
                            let proItem = imgLists[name].filter(val => val.id == id);
                            if (proItem.length) {
                                item.options.imgList[indexs] = proItem.map(
                                    ({ couponAcquiredNumber, id, couponInfo, couponId }) => {
                                        const item = {
                                            ...couponInfo
                                        };
                                        // receiveStatus:1表示已领完 2表示领取已达上限
                                        item.receiveStatus =
                                            item.couponTotal - couponAcquiredNumber == 0
                                                ? 1
                                                : item?.acquireLimit
                                                ? '2'
                                                : '';
                                        item.content = couponContent(item);
                                        item.id = id;
                                        item.couponId = couponId;
                                        return item;
                                    }
                                )[0];
                            } else {
                                item.options.imgList[indexs] = null;
                            }
                        });
                    }
                    if (name == 'groupbuy') {
                        if (item.options.addType == 1) {
                            item.options.imgList.forEach((id, indexs) => {
                                let proItem = imgLists[name].filter(val => val.id == id);
                                if (proItem.length) {
                                    item.options.imgList[indexs] = proItem[0];
                                } else {
                                    item.options.imgList[indexs] = null;
                                }
                            });
                        } else {
                            let typeList = ['have_group_goods_num', 'activity_end_time', 'activity_start_time'];
                            const groupAuto = await request('groupList', {
                                autogather: 1,
                                direction: 'desc',
                                activityType: item.options.groupType,
                                reorder: typeList[item.options.rule - 1]
                            });
                            item.options.imgList = isNotEmpty(groupAuto?.data) ? groupAuto?.data : [];
                        }
                    }
                    return item;
                })
            );
            // 过滤删除商品，当选择商品全部删除后，删除组件不再显示
            components.value = getData
                .map(item => {
                    item.options.imgList = item?.options?.imgList?.filter(fItem => fItem);
                    return item;
                })
                .filter(item => !item.options.imgList || item.options?.imgList.length > 0);
            setTimeout(() => {
                changeIframeHeight();
            }, 200);
        });
    }
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
